<?php

class News_Page_Main_Article_Edit_Exception extends News_Page_Main_Article_Exception {}
class News_Page_Main_Article_Edit_Invalid_Exception extends News_Page_Main_Article_Edit_Exception {}

class News_Page_Main_Article_Edit extends News_Page_Main_Article {

	protected function URL($array = array()){
		return parent::URL(array_merge(
			array($this->article->id(), 'edit'),
			$array
		));
	}

	public function rid($array = array()){
		return parent::rid(array_merge(
			array($this->article->id(), 'edit'),
			$array
		));
	}

	public function __construct($args){
		parent::__construct($args);

		$this->article = News_Article::GetByID($args['id']);

		$language = Authentication::getInstance()->user()->language();

		$article_id = $this->article->id();

		$this->form = new Form(
			array('news','article', $article_id, 'edit'), $this->URL());

		$title = Form_Field::Create('title','text');
		$title->title($language->translate(array('news','article','title')));
		$title->value($this->article->title());
		$title->validate('not_empty');
		$this->form->add($title);

		$date = Form_Field::Create('date', 'timedate');
		$date->title($language->translate(array('news','article','date')));
		$date->value($this->article->date());
		$this->form->add($date);

		$body = Form_Field::Create('body',array('richtext','textarea'));
		$body->title($language->translate(array('news','article','body')));
		$body->value($this->article->body());
		$this->form->add($body);

		$continue = Form_Field::Create('continue','checkbox');
		$continue->title($language->translate(array('news','article','continue')));
		
		$cont = isset($_SESSION['news']['article'][$this->article->id()]['continue']) 
				? $_SESSION['news']['article'][$this->article->id()]['continue'] 
				: false;

		$continue->value($cont);
		$this->form->add($continue);

		$submit = Form_Field::Create('submit','submit');
		$submit->title($language->translate(array('news','article','update')));

		$this->form->add($submit);
	}

	public function run(){
		parent::run();
		$this->form->run();

		try {
			$data = $this->form->data();

			$this->article->update(array(
				'title' => $data['title'], 
				'body' => $data['body'],
				'date' => $data['date']
			));

			if($data['continue']){
				$_SESSION['news']['article'][$this->article->id()]['continue'] = true;
				CMS::Redirect($this->URL());
			} else {
				unset($_SESSION['news']['article'][$this->article->id()]['continue']);
				CMS::Redirect(parent::URL(array($this->article->id(),'view')));
			}
		} catch(Exception $e){}
	}

	public static function Load($args){
		return new News_Page_Main_Article_Edit($args);

	}

	public function output($child = null){
		$template = Output::getInstance()->Template(array('news','page','article','edit'));
		$template->title = $this->article->title();
		$template->form = $this->form->output();
		return parent::output($template);
	}

}
